﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace Mimoza.PluginLayer
{
    /// <summary>
    ///  Execute plugins manager.
    /// </summary>    
    public class ExecutePluginManager
    {
        public const string LocalHostPluginId = "Mimoza.LocalHostPlugin.ExecutePlugin";

        public ExecutePluginManager()
        {
        }

        /// <summary>
        /// Initialize plugin manager to use application directory.
        /// </summary>
        public void Init()
        {
            Init("");
        }

        /// <summary>
        /// Initialize plugin manager to use application directory + sub directory.
        /// </summary>
        public void Init(string subDirectory)
        {
            string path = Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName;
            path = Path.GetDirectoryName(path);
            if (subDirectory != null && subDirectory != "")
            {
                path += ("/" + subDirectory);
            }

            m_workingPath = path;

            LoadByXmls(path);
        }

        /// <summary>
        /// Shutdown manager and all plugins.
        /// </summary>
        public void Shutdown()
        {
            foreach (IExecutePlugin plugin in m_plugins.Values)
            {
                if (plugin is IDisposable)
                {
                    (plugin as IDisposable).Dispose();
                }
            }
        }

        public IExecutePlugin Get(string pluginIdentity)
        {
            IExecutePlugin plugin = null;

            if (string.IsNullOrEmpty(pluginIdentity)) return null; 
            lock (m_plugins)
            {
                if (m_plugins.ContainsKey(pluginIdentity) == true)
                {
                    plugin = m_plugins[pluginIdentity];
                }
            }            
            return plugin;
        }

        private void LoadByXmls(string path)
        {
            foreach (string file in Directory.GetFiles(path, "*.xml"))
            {
                PluginLoader loader = new PluginLoader();
                loader.Init(file);
                foreach(IExecutePlugin executePlugin in loader.ExecutePlugins)
                {
                    m_plugins[executePlugin.PluginId] = executePlugin;
                }
            }
        }

        Dictionary<string, IExecutePlugin> m_plugins = new Dictionary<string, IExecutePlugin>();
        string m_workingPath;
    }
}
